module ui {

    export class LoadingUI extends egret.Sprite implements RES.PromiseTaskReporter {

        public static LOAD_IMG_COMPLETE: string = "loading_img_complete";

        private loadingTrack: egret.Sprite;
        private trackWidth: number = 300;
        private trackHeight: number = 20;
        private loading: egret.Sprite;
        private margin: number = 3;

        private loadBg: egret.Bitmap;

        public constructor() {
            super();
            this.loadImg();
        }

        private loadImg(): void {
            let imageLoader: egret.ImageLoader = new egret.ImageLoader();
            imageLoader.addEventListener(egret.Event.COMPLETE, this.loadCompleteHandler, this);
            imageLoader.load("resource/assets/GameRes/common/loading.jpg");

            manager.StatisticsManager.sceneCount(1001)
        }

        private loadCompleteHandler(event: egret.Event): void {
            let imageLoader = <egret.ImageLoader>event.currentTarget;
            imageLoader.removeEventListener(egret.Event.COMPLETE, this.loadCompleteHandler, this);
            let texture = new egret.Texture();
            texture._setBitmapData(imageLoader.data);
            this.loadBg = new egret.Bitmap();
            this.loadBg.texture = texture;
            this.loadBg.width = manager.DisplayManager.STAGE_WIDTH;
            this.loadBg.height = manager.DisplayManager.STAGE_HEIGHT;
            this.addChild(this.loadBg);
            this.createView();
            this.dispatchEvent(new egret.Event(LoadingUI.LOAD_IMG_COMPLETE));
        }

        private createView(): void {
            this.loadingTrack = new egret.Sprite();
            this.loadingTrack.graphics.beginFill(0xffffff);
            this.loadingTrack.graphics.drawRect(0, 0, this.trackWidth, this.trackHeight);
            this.loadingTrack.graphics.endFill();
            this.addChild(this.loadingTrack);

            this.loadingTrack.x = manager.DisplayManager.STAGE_WIDTH - this.loadingTrack.width >> 1;
            this.loadingTrack.y = manager.DisplayManager.STAGE_HEIGHT - 500;

            this.loading = new egret.Sprite();
            this.loading.graphics.beginFill(0x0);
            this.loading.graphics.drawRect(0, 0, this.margin, this.trackHeight - this.margin);
            this.loading.graphics.endFill();
            this.addChild(this.loading);
            this.loading.x = this.margin / 2 + this.loadingTrack.x;
            this.loading.y = this.margin / 2 + this.loadingTrack.y;


            this.x = this.y = 0;
        }

        public onProgress(current: number, total: number): void {
            let width: number = (this.trackWidth - 2 * this.margin) * current / total;
            this.loading.width = width;
            this.loading.scaleX = width / this.margin;
        }
    }
}